package com.huodongrili.calender;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huodongrili.calender.data.Constant;
import com.huodongrili.calender.data.EventsData;
import com.huodongrili.calender.model.Event;
import com.huodongrili.calender.util.ECLog;
import com.huodongrili.calender.widget.PullToRefreshListView;
import com.huodongrili.calender.widget.PullToRefreshListView.OnRefreshListener;

public class EventsFragment extends ListFragment implements
		OnItemClickListener, OnRefreshListener {

	private List<Event> events;
	private EventAdapter mAdapter;
	private PullToRefreshListView mListView;
	private ImageView mTipImg;
	private LinearLayout mLoadlay;
	private ImageView mEmptyText;

	private int mYear;
	private int mMonth;
	private int mDay;

	private Date mCurrentDate;

	private LoadEventTask mTask;
	private int mStartIndex = 0;
	private volatile int mNowIndex = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Calendar c = Calendar.getInstance();

		mMonth = c.get(Calendar.MONTH) + 1;
		mYear = c.get(Calendar.YEAR);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		// dateFormat = new SimpleDateFormat(Constant.DATE_FORMAT);
		mCurrentDate = new Date(mYear, mMonth - 1, mDay);

		events = new ArrayList<Event>();
		mAdapter = new EventAdapter();

		setListAdapter(mAdapter);

		mTask = new LoadEventTask();
		mTask.importIndex = mNowIndex;
		mTask.execute();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.fragment_events, container, false);

		mTipImg = (ImageView) v.findViewById(R.id.no_data);
		mLoadlay = (LinearLayout) v.findViewById(R.id.load_pane);
		mEmptyText = (ImageView) v.findViewById(R.id.empty_event);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mListView = (PullToRefreshListView) getListView();
		mListView.setOnItemClickListener(this);
		mListView.setonRefreshListener(this);

	}

	public void changedData(int position, int year, int month, int day) {

		mNowIndex = position;

		if (BuildConfig.DEBUG) {
			ECLog.debug("changedData :year=" + year + ",month=" + month
					+ ",day=" + day);
			ECLog.debug("the today year=" + mCurrentDate.getYear() + ",month="
					+ mCurrentDate.getMonth() + ",day="
					+ mCurrentDate.getDate());
		}

		mStartIndex = 0;

		if (events != null)
			events.clear();

		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}

		// TODO
		// mListView.setFooterVisible(View.VISIBLE);

		mYear = year;
		mMonth = month;
		mDay = day;

		Date d = new Date(year, month - 1, day);

		int comValue = d.compareTo(mCurrentDate);
		if (comValue >= 0) {

			if (BuildConfig.DEBUG) {
				ECLog.debug("changedData date is big.....");
			}

			if (isOutScope(year, month)) {
				if (BuildConfig.DEBUG) {
					ECLog.debug("changedData date is out of scope.....");
				}

				mListView.setVisibility(View.GONE);
				mTipImg.setImageResource(R.drawable.early_tips);
				mTipImg.setVisibility(View.VISIBLE);
				mLoadlay.setVisibility(View.GONE);
				mEmptyText.setVisibility(View.GONE);

			} else {

				if (BuildConfig.DEBUG) {
					ECLog.debug("changedData date is big and in scope.....");
				}

				mTask.cancel(true);
				mTask.isExcute = false;
				mTask = null;

				mListView.setVisibility(View.GONE);
				mTipImg.setVisibility(View.GONE);
				mLoadlay.setVisibility(View.VISIBLE);
				mEmptyText.setVisibility(View.GONE);

				mTask = new LoadEventTask();
				mTask.importIndex = mNowIndex;
				mTask.execute();

			}

		} else {
			if (BuildConfig.DEBUG) {
				ECLog.debug("changedData date is late.....");
			}
			mListView.setVisibility(View.GONE);
			mLoadlay.setVisibility(View.GONE);
			mEmptyText.setVisibility(View.GONE);
			mTipImg.setImageResource(R.drawable.late_tips);
			mTipImg.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		if (arg2 == 0)
			return;

		Event event = (Event) mAdapter.getItem(arg2 - 1);

		Intent i = new Intent(getActivity(), EventDetailActivity.class);
		i.putExtra(Constant.EVENT_ENTRY, event);
		startActivity(i);

	}

	@Override
	public void onRefresh() {

		LoadMoreTask task = new LoadMoreTask();

		task.importIndex = mNowIndex;
		task.execute();
	}

	private class LoadEventTask extends AsyncTask<Void, Void, List<Event>> {

		public boolean isExcute = true;
		public int importIndex = 0;

		@Override
		protected List<Event> doInBackground(Void... params) {

			if (BuildConfig.DEBUG) {
				ECLog.debug("the inint load....");
			}

			EventsData event = new EventsData(getActivity()
					.getApplicationContext());

			Date date = new Date(mYear - 1900, mMonth - 1, mDay);
			SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_FORMAT);
			String strV = sdf.format(date);
			if (BuildConfig.DEBUG) {
				ECLog.debug("the EventsData query param: " + strV);
			}

			List<Event> result = event.getEventsByTime(mStartIndex,
					Constant.E_LIMIT, strV);

			/*
			 * try { Thread.sleep(1000); } catch (InterruptedException e) { }
			 */

			return result;
		}

		@Override
		protected void onPostExecute(List<Event> result) {

			if (!isExcute)
				return;

			if (importIndex != mNowIndex) {
				return;
			}

			mTipImg.setVisibility(View.GONE);
			mLoadlay.setVisibility(View.GONE);

			if (result == null) {
				mEmptyText.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
				return;
			}

			int count = result.size();
			if (count <= 0) {
				mEmptyText.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
				return;
			}

			events.addAll(result);
			mAdapter.notifyDataSetChanged();
			mStartIndex = mStartIndex + count;

			result.clear();

			mListView.setVisibility(View.VISIBLE);

		}
	}

	private class LoadMoreTask extends AsyncTask<Void, Void, List<Event>> {

		public int importIndex = 0;

		@Override
		protected List<Event> doInBackground(Void... params) {

			if (BuildConfig.DEBUG) {
				ECLog.debug("the LoadMoreTask load....");
			}

			EventsData event = new EventsData(getActivity()
					.getApplicationContext());

			Date date = new Date(mYear - 1900, mMonth - 1, mDay);
			SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_FORMAT);
			String strV = sdf.format(date);
			if (BuildConfig.DEBUG) {
				ECLog.debug("the EventsData query param: " + strV);
			}

			List<Event> result = event.getEventsByTime(mStartIndex,
					Constant.E_LIMIT, strV);

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}

			return result;
		}

		@Override
		protected void onPostExecute(List<Event> result) {

			mListView.onRefreshComplete();

			if (importIndex != mNowIndex) {
				return;
			}

			if (result == null) {

				Toast.makeText(getActivity(), R.string.no_more,
						Toast.LENGTH_SHORT).show();

				return;
			}

			int count = result.size();
			if (count <= 0) {

				Toast.makeText(getActivity(), R.string.no_more,
						Toast.LENGTH_SHORT).show();
				return;
			}

			events.addAll(result);
			mAdapter.notifyDataSetChanged();

			mStartIndex = mStartIndex + count;

			result.clear();

		}

	}

	private class EventAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return events.size();
		}

		@Override
		public Object getItem(int position) {
			return events.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.event_item, parent, false);

			}

			LinearLayout pane = (LinearLayout) convertView
					.findViewById(R.id.item_pane);
			ImageView imgFlg = (ImageView) convertView
					.findViewById(R.id.img_flg);
			TextView time = (TextView) convertView.findViewById(R.id.time);
			TextView title = (TextView) convertView.findViewById(R.id.title);
			TextView power = (TextView) convertView.findViewById(R.id.power);
			TextView score = (TextView) convertView
					.findViewById(R.id.power_score);

			Resources res = getResources();

			if (position % 2 == 0) {
				pane.setBackgroundColor(res.getColor(R.color.grey_light));
			} else {
				pane.setBackgroundColor(res.getColor(R.color.white));
			}

			Event event = (Event) getItem(position);

			title.setText(event.getTitle());
			time.setText(event.getSTime());

			String sort = event.getSort();
			if (sort == null || sort.length() <= 0) {
				power.setText(R.string.e_str);
			} else {
				power.setText(sort);
			}

			int po = event.getPoint();

			score.setText(String.valueOf(po));

			if (po >= 90) {
				int c = res.getColor(R.color.sort_red);
				imgFlg.setBackgroundColor(c);
				power.setTextColor(c);
				score.setTextColor(c);
			} else if (po >= 80) {
				int c = res.getColor(R.color.sort_blue);
				imgFlg.setBackgroundColor(c);
				power.setTextColor(c);
				score.setTextColor(c);
			} else {
				int c = res.getColor(R.color.sort_green);
				imgFlg.setBackgroundColor(c);
				power.setTextColor(c);
				score.setTextColor(c);
			}

			return convertView;
		}

	}

	private boolean isOutScope(int year, int month) {

		boolean isOut = false;

		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		int currentYear = c.get(Calendar.YEAR);

		int outFlg = 0;
		int outYear = year;

		if (currentMonth == 11) {

			outFlg = 1;

			if (currentYear < year) {

				if ((currentYear + 1) == year) {
					if (month >= outFlg) {
						isOut = true;
					} else {
						isOut = false;
					}
				} else {
					isOut = true;
				}

			} else if (currentYear == year) {
				isOut = false;
			} else if (currentYear > year) {
				isOut = false;
			}

		} else if (currentMonth == 12) {

			outFlg = 2;

			if (currentYear < year) {

				if ((currentYear + 1) == year) {
					if (month >= outFlg) {
						isOut = true;
					} else {
						isOut = false;
					}
				} else {
					isOut = true;
				}

			} else if (currentYear == year) {
				isOut = false;
			} else if (currentYear > year) {
				isOut = false;
			}

		} else {

			if (year > currentYear) {
				isOut = true;
			} else {
				outFlg = currentMonth + 2;

				if (month >= outFlg) {
					isOut = true;
				}
			}

		}

		return isOut;
	}

}
